﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microhard.Permission.Interface;
using Microhard.Core;
using Microhard.Core.Security;
using System.Web;
using System.Web.Routing;

namespace Microhard.Permission.MVCFilter
{
    public class MVCSSOFilter : ActionFilterAttribute, IMvcFilter
    {
        private string _ssoStrParmName;
        private IUser user = IoC.Resolve<IUser>();
        private bool _isRedirect = true;

        public MVCSSOFilter(string ssoStrParmName)
        {
            _ssoStrParmName = ssoStrParmName;
        }

        public MVCSSOFilter(string ssoStrParmName, bool isRedirect)
        {
            _ssoStrParmName = ssoStrParmName;
            _isRedirect = isRedirect;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //传递参数是否合法
            var pms = filterContext.RequestContext.HttpContext.Request.QueryString[_ssoStrParmName];
            if (pms == null || string.IsNullOrEmpty(pms.ToString()))
            {
                this.RedirectToPage(filterContext);
            }
            string strSSO = HttpUtility.UrlDecode(pms.ToString());
            strSSO = strSSO.Replace(" ", "+");
            //解析出用户名
            //获得密钥
            string ssokey = System.Configuration.ConfigurationManager.AppSettings["SSOKey"];
            string useName = EncDec.Decrypt(strSSO, ssokey);
            if (string.IsNullOrEmpty(useName))
            {
                this.RedirectToPage(filterContext);
            }
            //登录
            var userinfo = user.GetUserByName(useName);
            if (userinfo == null || userinfo.UserName != useName)
            {
                this.RedirectToPage(filterContext);
            }
            user.SignIn(useName, true);
            //跳转到系统首页
            if (_isRedirect)
            {
                filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary {
                {"controller", "Account"}, {"action", "Nav"},{"area",string.Empty}});
            }
        }

        public void RedirectToPage(ActionExecutingContext filterContext)
        {
            user.SignOut();
            filterContext.HttpContext.Session.Clear();
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult()
                {
                    Data = "单点登录数据错误，请联系系统管理员",
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                var ad = new ViewResult();
                ad.ViewName = "SSOError";
                filterContext.Result = ad;
            }
        }
    }
}
